package juc.threadpool;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.security.cert.TrustAnchor;
import java.util.concurrent.*;

/**
 * @author 况祥彬
 * @date 2020/12/11 16:14
 **/

/**
 * 基本使用schedule
 */
@Slf4j
class demo1 {
    public static void main(String[] args) {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(0);
        scheduledExecutorService.schedule(() -> {
            try {
                int i = 1 / 0;
            } catch (Exception e) {
                e.printStackTrace();
            }
            log.debug("task1");
        }, 1, TimeUnit.SECONDS);

        scheduledExecutorService.schedule(() -> {
            log.debug("task2");
        }, 1, TimeUnit.SECONDS);

    }
}

/**
 * 处理异常
 */
@Slf4j
class demo1ss {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(1);
        Future<Boolean> future = scheduled.submit(() -> {
            int i = 1 / 0;
            log.debug("task1");
            return true;
        });
        System.out.println(future.get());
    }
}

/**
 * scheduleAtFixedRate和scheduleWithFixedDelay
 */
@Slf4j
class demo2s {
    public static void main(String[] args) {
        ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(0);
//        scheduled.scheduleAtFixedRate(() -> {
//            log.debug("starting");
//            try {
//                TimeUnit.SECONDS.sleep(1);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }, 1, 1, TimeUnit.SECONDS);
        scheduled.scheduleWithFixedDelay(() -> {
            log.debug("starting");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, 1, 1, TimeUnit.SECONDS);
    }
}

class demo4{
    public static void main(String[] args) {
        ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1);
        ScheduledFuture<?> scheduledFuture = scheduled.schedule(() -> {
            System.out.println("starting");
        }, 1, TimeUnit.SECONDS);
        scheduledFuture.cancel(true);
        System.out.println(scheduledFuture.isCancelled());
        System.out.println(scheduledFuture.isDone());

    }
}
public class MyScheduledThreadPool {

}